<template>

  <div class="app-container">
    <el-row>
      <el-col :span="24"><el-button type="primary" size="mini" @click="handleAdd">添加</el-button></el-col>
    </el-row>

    <el-table ref="table" :data="tableData"
      border
      :row-key="`id`"
      style="width: 100%"
      lazy
      :load="load"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      @expand-change="expandChange">
      <!-- <el-table-column type="expand" label="#" width="50"></el-table-column> -->
      <el-table-column prop="id" label="id"  align="left" width="130"></el-table-column>
      <el-table-column prop="clazz" label="分类"  align="center"></el-table-column>
      <el-table-column prop="key" label="编码" align="center"></el-table-column>
      <el-table-column prop="value" label="值" align="center" ></el-table-column>
      <el-table-column prop="name" label="名称" align="center" ></el-table-column>
      <el-table-column prop="type" label="类型" align="center" ></el-table-column>
      <el-table-column prop="gmtCreate" label="创建时间" align="center" ></el-table-column>
      <el-table-column label="操作" align="center" >
        <template slot-scope="scope">
          <!-- <div>
            {{scope.row}}
          </div> -->
          <el-button v-if="scope.row.hasChildren" size="mini" type="text" @click="rowAdd(scope.row)">添加</el-button>
          <el-button v-if="scope.row.modifiable==1" size="mini" type="text" @click="edit(scope.row)">编辑</el-button>
          <el-button v-if="scope.row.deletable==1" class="text-red" size="mini" type="text" @click="deleteRow(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog title="添加" :visible="dialogFormVisible" :before-close="handleClose" :close-on-click-modal="false">
      <el-form :model="form">
        <el-form-item label="分类：" :label-width="formLabelWidth">
          <el-input v-model="form.clazz" :disabled="isDisabled" size="mini" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="编码：" :label-width="formLabelWidth">
          <el-input v-model="form.key" size="mini" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="值：" :label-width="formLabelWidth">
          <el-input v-model="form.value" size="mini" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="名称：" :label-width="formLabelWidth">
          <el-input v-model="form.name" size="mini" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="排序：" :label-width="formLabelWidth">
          <el-input v-model="form.sort" size="mini" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="类型：" :label-width="formLabelWidth">
          <!-- <el-input v-model="form.type" size="mini" autocomplete="off"></el-input> -->
          <el-select
                v-model="form.type"
                size="mini"
                placeholder="请选择类型"
                >
                <el-option
                  v-for="item in typeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
        </el-form-item>
        <el-form-item label="是否可删除：" :label-width="formLabelWidth">
          <el-radio-group v-model="form.deletable">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否可修改：" :label-width="formLabelWidth">
          <el-radio-group v-model="form.modifiable">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {getList, getDictChildren, createDict, deleteDict, updateDict} from '@/api/dictionary'
export default {
    data() {
      return {
        queryParams: {
          page: 1,
          pageSize: 20
        },
        tableData: [],
        total: 0,
        dialogFormVisible: false,
        formLabelWidth: '120px',
        form: {
          deletable: 0,
          modifiable: 0
        },
        isDisabled: true,
        resolveObj: undefined,
        typeOptions: [
          {
            label: 'string',
            value: 'string'
          },{
            lable: 'int',
            value: 'int'
          }
        ],
        loadNodeMap: new Map(),  // 缓存懒加载过的父节点
        parentNode: {},   // 当前父节点
      }
    },
    computed: {

    },
    mounted() {
      this.getList()
    },
    methods: {
      async getList() {
        try {
          const res = await getList(this.queryParams);
          if(res.code == 1) {
            const list = res.data.map(item => {
              item.hasChildren = true;
              item.children = []
              return item;
            })
            this.tableData = list;
            this.total = res.total;
          }
        } catch (error) {

        }
      },
      async createDict(data, cb) {
        try {
          const res = await createDict(data);
          if(res.code == 1) {
            cb&&cb()
          }
        } catch (error) {

        }
      },
      // 清空缓存的子节点， 以便刷新界面
      resetLazyTree() {
        this.$set(this.$refs.table.store.states, 'lazyTreeNodeMap', {})
      },
      load(tree, treeNode, resolve){
        // 将当前操作报存起来
        this.loadNodeMap.set(tree.id, {tree, treeNode, resolve})
        getDictChildren({clazz: tree.key}).then(res => {
          const list = res.data.map(item => {
            item.id = `${tree.id}-${item.id}`
            return item;
          })
          this.resolveObj = resolve
          resolve(list)
        })
      },
      expandChange(a,b) {
        // console.log(a,b)
        const idx = this.tableData.findIndex(item => a.id === item.id);
      },
      // 全局添加
      handleAdd() {
        // 添加一级分类
        this.dialogFormVisible = true
        this.form.clazz = 'clazz'
      },
      // 行添加
      rowAdd(row) {
        this.parentNode = row;
        this.form.clazz = row.key;
        this.dialogFormVisible = true
      },
      // 提交表单
      submit() {
        // if(this.isDisabled) {
        //   this.form.clazz = 'clazz'
        // }
        if(this.form.id) {
          let id = this.form.id
          if(!this.form.hasChildren) {
            id = this.form.id.split("-")[1]
          }
          Object.assign(this.form,{id})
          updateDict(this.form).then(res => {
            if(res.code == 1) {
              this.$message({
                type: 'success',
                message: '更新成功'
              })
              if(!this.form.hasChildren) {
                this._reRenderChildrenNodeAfterAdd()
              }else{
                this.getList()
              }
              this.$forceUpdate()
              this.closeDialog()
              // this.reload()
            }
          })
        }else{
          this.createDict(this.form, _=> {
            this.$message({
              type: 'success',
              message: '添加成功'
            })
            this.getList()
            if(!this.form.hasChildren) {
              this._reRenderChildrenNodeAfterAdd()
            }
            this.$forceUpdate()
            this.closeDialog()
            // this.reload()
          })
        }
      },
      // 重置刷新子元素
      _reRenderChildrenNodeAfterAdd(cb) {
        if (this.loadNodeMap.has(this.parentNode.id)) {
          const {tree, resolve} = this.loadNodeMap.get(this.parentNode.id);
          this.resetLazyTree()
          this.load(tree, {}, resolve)
          tree.hasChildren = true
          cb&&cb()
        }else{
          this.parentNode.hasChildren = true
        }
      },
      // 打开编辑dialog
      edit(row) {
        this.form = row;
        let id = row.id
        let pid = row.id;
        if(!row.hasChildren) {
          id = row.id.split("-")[1]
          pid = row.id.split("-")[0]
          this.parentNode = this.selectParentNode(pid);
        }else{
          this.parentNode = row;
        }
        this.dialogFormVisible = true;
      },
      // 打开详情dialog
      showDetail(row) {
        this.form = row;
        this.dialogFormVisible = true;
      },
      deleteRow(row) {
        let id = row.id
        let pid = row.id;
        if(!row.hasChildren) {
          id = row.id.split("-")[1]
          pid = row.id.split("-")[0]
          this.parentNode = this.selectParentNode(pid);
        }else{
          this.parentNode = row;
        }
        console.log(row,this.parentNode)
        this.$confirm('是否确认删除id为"' + id + '"的数据项？').then(function() {
          return deleteDict({id});
        }).then(() => {
          if(!row.hasChildren) {
            this._reRenderChildrenNodeAfterAdd()
            // this.load(row,{}, this.resolveObj)
          }else{
            this.getList();
          }
          this.$forceUpdate()
          this.$message({
            type: 'success',
            message: '删除成功'
          })
          // this.reload()
        }).catch(() => {});
      },
      selectParentNode(id) {
        return this.tableData.find(item=> item.id == id)
      },
      reload() {
        window.location.reload()
      },
      handleClose(done) {
        this.closeDialog()
      },
      closeDialog() {
        this.dialogFormVisible = false;
        this.form = {
          clazz: undefined,
          key: undefined,
          value: undefined,
          name: undefined,
          type: undefined,
          sort: undefined,
          deletable: 0,
          modifiable: 0
        }
      }
    }
}
</script>
<style lang="scss" scoped>
  .el-row {
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
  }
.text-red {
  color: red;
}
</style>
